import requests


class MyRequest:
    def __init__(self, url, method='get', data=None, headers=None, is_json=False):
        self.url = url
        self.data = data
        self.headers = headers
        self.is_json = is_json
        if hasattr(self, method.lower()):
            getattr(self, method.lower())()

    def get(self):
        try:
            req = requests.get(self.url, self.data, headers=self.headers).json()
        except Exception as e:
            self.response = {"error_code": "-1", "msg": "接口不通"}
        else:
            self.response = req

    def post(self):
        try:
            if self.is_json:
                req = requests.post(self.url, json=self.data, headers=self.headers).json()
            else:
                req = requests.post(self.url, data=self.data, headers=self.headers).json()
        except Exception as e:
            self.response = {"error_code": "-1", "msg": "接口不通"}
        else:
            self.response = req


if __name__ == '__main__':
    import jsonpath

    # login = MyRequest('http://127.0.0.1:8000/api/login', method='post', data={"username": "yigl03", "password": "yigl03"}, is_json=True)
    login = MyRequest('http://api.nnzhp.cn/api/user/login', method='post',
                      data={"username": "niuhanyang", "passwd": "aA123456"})
    cookie = 'niuhanyang=' + str(jsonpath.jsonpath(login.response, '$..sign')[0])
    print(cookie)
    gold = MyRequest('http://api.nnzhp.cn/api/user/gold_add', method='post', headers={"cookie": cookie},
                     data={"stu_id": "100010879", "gold": "10"})
    print(gold.response)
    # print(jsonpath.jsonpath(login.response,"$..msg"))
